<template>
  <Header />
  <div class="main">
    <!-- 设置按钮 -->
    <div class="settings-button" @click="showSettingsDrawer = true">
      <el-button type="primary" size="primary">
        <IconProjectSetting />
      </el-button>
    </div>

    <div class="project" v-loading="loading">
      <div class="project-header">
        <div class="project-title">
          <h1 class="text-24px fw-600">项目列表</h1>
          <span class="project-count">共 {{ projectList.length }} 个项目</span>
        </div>
        <div class="project-actions">
          <el-button type="primary" @click="showAddProjectVisible = true">
            <IconAddMember class="mr-4px" />
            新建项目
          </el-button>
        </div>
      </div>

      <div class="project-list mt-16px">
        <div v-for="project in projectList" class="project-item" @click="handleProject(project.projectId)">
          <div class="project-item-icon">
            <img src="@/assets/projectIcon.jpg" alt="项目图标">
          </div>
          <div class="project-item-title">
            <h3>{{ project.projectName }}</h3>
          </div>
          <div class="project-item-desc">
            {{ project.projectDesc }}
          </div>
          <div class="project-item-footer">
            <span class="creator">创建人：{{ project.creator }}</span>
            <span class="create-time">创建时间：{{ formatDayTime(project.createTime) }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
  <el-dialog v-model="showAddProjectVisible" title="新建项目" width="450">
    <el-form :model="form" :rules="rules" label-width="auto" ref="formRef">
      <el-form-item label="项目名称:" prop="name">
        <el-input v-model="form.name" placeholder="请输入项目名称" />
      </el-form-item>
      <el-form-item label="项目描述:">
        <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入项目描述">
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleAddProject">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 设置抽屉 -->
  <el-drawer v-model="showSettingsDrawer" title="系统设置" direction="rtl" size="400px" :before-close="handleDrawerClose"
    custom-class="settings-drawer">
    <div class="settings-content">
      <div class="settings-section">
        <h3 class="section-title">水印设置</h3>
        <div class="watermark-settings">
          <el-switch v-model="watermarkEnabled" active-text="显示水印" inactive-text="关闭水印" @change="toggleWatermark" />
        </div>
      </div>
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
import router from '@/router';
import { ref, onMounted, onUnmounted, reactive, computed } from 'vue';
import { getProjectListApi, addProjectApi } from '@/common/apis/project';
import { formatDayTime } from '@/common/utils/datetime.ts';
import type { ProjectList } from '@/common/apis/project/type';
import Header from '@/common/components/Header.vue';
import { useUserStore } from "@/store/modules/user.ts";
const userStore = useUserStore();
const projectList = ref<ProjectList[]>([]); // 存储项目列表
const loading = ref(false); // 加载状态
const showAddProjectVisible = ref(false);
const formRef = ref(null);

// 设置抽屉相关
const showSettingsDrawer = ref(false);
const watermarkEnabled = ref(true);

// 监听水印状态变化，同步按钮状态
const handleWatermarkStatusUpdate = (event: CustomEvent) => {
  watermarkEnabled.value = event.detail.enabled;
};
const form = reactive({
  name: '',
  description: '',
});

const rules = reactive({
  name: [
    { required: true, message: '请输入项目名称', trigger: 'blur' },
  ],
});


const handleProject = (id: any) => {
  router.push(`/project/${id}`);
};

// 获取项目列表
const getProjectList = async () => {
  try {
    loading.value = true;
    const { data } = await getProjectListApi(); // 调用API获取项目列表
    projectList.value = data || []; // 存储项目列表
  } catch (error) {
  } finally {
    loading.value = false;
  }
};

const handleClose = () => {
  showAddProjectVisible.value = false;
  formRef.value?.resetFields();
  Object.assign(form, {
    name: '',
    description: '',
  });
};

const handleAddProject = async () => {
  const { name, description } = form;
  try {
    handleClose();
    loading.value = true;
    const res = await addProjectApi({
      creator_id: userStore.getUserInfo()?.id,
      name,
      description,
    });
    await init();
    ElMessage.success({ message: `${res.message}` });
  } catch (error) {
  } finally {
    loading.value = false;
  }
};

const init = async () => {
  await getProjectList(); // 获取项目列表
};

// 设置相关处理函数
const handleDrawerClose = () => {
  showSettingsDrawer.value = false;
};


const toggleWatermark = (enabled: boolean | string | number) => {
  const isEnabled = Boolean(enabled);
  // 发送水印切换事件到 App.vue
  window.dispatchEvent(new CustomEvent('watermark-toggle', {
    detail: { enabled: isEnabled }
  }));
  ElMessage.success({ message: isEnabled ? '水印已开启' : '水印已关闭' });
};

onMounted(async () => {
  await init();

  // 添加水印状态监听
  window.addEventListener('watermark-status-update', handleWatermarkStatusUpdate);

  // 检查是否已经显示过通知
  if (!userStore.hasShownGiteeNotification) {
    ElNotification.success({
      title: 'gitee链接',
      message: "https://gitee.com/lsy-points/APIHub",
      position: 'bottom-right',
      duration: 0,
      onClick: () => {
        window.open('https://gitee.com/lsy-points/APIHub', '_blank');
      },
      customClass: 'clickable-notification'
    });

    // 标记为已显示
    userStore.setGiteeNotificationShown();
  }
});

onUnmounted(() => {
  // 移除水印状态监听
  window.removeEventListener('watermark-status-update', handleWatermarkStatusUpdate);
});
</script>

<style lang="less" scoped>
.main {
  background: var(--bg-primary);
  min-height: calc(100vh - 64px);
  transition: background-color 0.3s ease;

  .project {
    padding: 24px;
    background: var(--bg-primary);

    .project-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24px;
      padding-bottom: 16px;
      border-bottom: 1px solid var(--border-light);

      .project-title {
        display: flex;
        align-items: center;
        gap: 12px;

        h1 {
          color: var(--text-primary);
          margin: 0;
          font-size: 24px;
          font-weight: 600;
        }

        .project-count {
          color: var(--text-secondary);
          font-size: 14px;
          background: var(--bg-secondary);
          padding: 4px 12px;
          border-radius: 16px;
        }
      }

      .project-actions {
        display: flex;
        gap: 12px;

        .btn {
          display: flex;
          align-items: center;
          gap: 8px;
          padding: 10px 16px;
          border: none;
          border-radius: 8px;
          font-size: 14px;
          font-weight: 500;
          cursor: pointer;
          transition: all 0.3s ease;

          &.btn-primary {
            &:hover {
              background: var(--primary-dark);
              transform: translateY(-1px);
              box-shadow: var(--shadow-light);
            }
          }

          &.btn-secondary {
            background: var(--bg-secondary);
            color: var(--text-primary);
            border: 1px solid var(--border-color);

            &:hover {
              background: var(--bg-tertiary);
              border-color: var(--primary-color);
            }
          }
        }
      }
    }

    .project-list {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
      gap: 20px;
      grid-auto-rows: min-content;
      grid-auto-flow: row dense;
      overflow: auto;

      .project-item {
        background: var(--card-bg);
        border-radius: 12px;
        padding: 20px;
        box-shadow: var(--shadow-light);
        transition: all 0.3s ease;
        border: 1px solid var(--border-light);
        display: flex;
        flex-direction: column;
        gap: 12px;
        position: relative;
        cursor: pointer;

        &:hover {
          transform: translateY(-2px);
          box-shadow: var(--shadow-medium);
          background: var(--card-hover-bg);
        }

        // 项目图标
        .project-item-icon {
          display: flex;
          justify-content: center;
          margin-bottom: 8px;

          img {
            width: 60px;
            height: 60px;
            border-radius: 8px;
            object-fit: cover;
            border: 2px solid var(--border-light);
          }
        }

        // 项目标题
        .project-item-title {
          h3 {
            margin: 0;
            font-size: 18px;
            font-weight: 600;
            color: var(--text-primary);
            text-align: center;
            line-height: 1.4;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }

        // 项目描述
        .project-item-desc {
          color: var(--text-secondary);
          font-size: 14px;
          line-height: 1.5;
          text-align: center;
          margin: 8px 0;
          flex-grow: 1;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        // 项目底部信息
        .project-item-footer {
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 12px;
          color: var(--text-tertiary);
          margin-top: auto;
          padding-top: 12px;
          border-top: 1px solid var(--border-light);

          .creator,
          .create-time {
            background: var(--bg-secondary);
            padding: 4px 8px;
            border-radius: 4px;
            white-space: nowrap;
          }
        }
      }
    }
  }
}

// 设置按钮样式
.settings-button {
  position: fixed;
  right: 4px;
  top: 50%;
  transform: translateY(-50%);
  z-index: 1000;

  .el-button {
    box-shadow: var(--shadow-medium);
    transition: all 0.3s ease;

    &:hover {
      transform: scale(1.1);
      box-shadow: var(--shadow-heavy);
    }
  }
}

// 设置抽屉内容样式
.settings-content {
  padding: 0 16px;

  .settings-section {
    margin-bottom: 32px;

    .section-title {
      font-size: 16px;
      font-weight: 600;
      color: var(--text-primary);
      margin: 0 0 16px 0;
      padding-bottom: 8px;
      border-bottom: 1px solid var(--border-light);
    }


    .watermark-settings {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 12px 0;
    }

  }
}

:deep(.clickable-notification) {
  cursor: pointer;

  &:hover {
    background-color: var(--hover-bg);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
}
</style>